<template>
  <div>
    <el-dialog
      @close="close"
      :title="form.id ? '编辑' : '新增'"
      :visible="dialogVisible"
      width="700px"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="114px"
        class="demo-form"
      >
        <el-form-item label="内容密级" prop="secretLevel">
          <el-radio-group @change="rankChange" v-model="form.secretLevel">
            <el-radio label="A">A级</el-radio>
            <el-radio label="B">B级</el-radio>
            <el-radio label="C">C级</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            @change="selectType"
            v-model="form.type"
            placeholder="请选择类型"
          >
            <el-option
              v-for="item in typeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isSmallLaw" label="法规小分类" prop="lawType">
          <el-select placeholder="请选择小分类" v-model="form.lawType">
            <el-option
              v-for="item in lawType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="URl" prop="url">
          <el-input v-model="form.url" placeholder="请输入网址"></el-input>
        </el-form-item>
        <el-form-item label="爬取标签" prop="labelList">
          <el-autocomplete
            v-model="label"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>

          <div class="tag-box">
            <el-tag
              @close="removeTag(tag)"
              class="tag"
              v-for="tag in form.labelList"
              :key="tag.id"
              closable
              :type="tag.type"
            >
              {{ tag.value }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="总条数" prop="sum">
          <el-input
            @input="sumInput"
            v-model.number="form.sum"
            placeholder="请输入总条数"
          ></el-input>
        </el-form-item>
        <el-form-item label="执行周期(min)" prop="cycle">
          <el-input
            @input="cycleInput"
            v-model.number="form.cycle"
            placeholder="请输入执行周期"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="end">
            <el-button type="primary" @click="saveFn">保存</el-button>
            <!-- <el-button @click="resetForm('form')"></el-button> -->
            <el-button @click="close">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCrawlerEditApi,
  getCrawlerAddApi,
} from "@/wss/newApi_3-24/work/crawler.js";
import { lawType, changeLawType, changeType } from "@/wss/utils/wss.js";
// 标签
import { getlabelListApi } from "@/wss/newApi_3-24/base/label.js";
// import { getLawListTitleApi } from "@/wss/newApi_3-24/doc/law.js";
import { getLawListTitleApi } from "@/wss/newApi_3-24/doc/law.js";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    // url的验证
    var validatePass = (rule, value, callback) => {
      let rep =
        /^(https?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i;
      if (!rep.test(value)) {
        callback(new Error("URL格式不对"));
      } else {
        callback();
      }
    };

    return {
      // 显示的选择
      selectList: [],
      // 选择的标签
      label: "",
      labelShowList: [],
      typeArr: [
        {
          value: "1",
          label: "法规",
        },
        {
          value: "4",
          label: "问答",
        },
        {
          value: "3",
          label: "头条",
        },
      ],
      lawType: lawType,
      isSmallLaw: false,
      //   表单数据
      form: {
        id: "",
        source: "",
        type: "",
        status: "",
        url: "",
        remark: "",
        sum: "",
        current: "",
        lawType: "",
        lastTime: "",
        cycle: "",
        secretLevel: "A",
        labelList: [],
      },
      // 表单的验证
      rules: {
        lawType: [{ required: true, message: "请选择法规", trigger: "change" }],
        source: [{ required: true, message: "请输入来源", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        // secretLevel: [
        //   { required: true, message: "请选择等级", trigger: "change" },
        // ],
        url: [
          {
            validator: validatePass,
            required: true,
            message: "请输入网址",
            trigger: "blur",
          },
        ],
        sum: [
          {
            required: true,
            message: "请输入总条数(0-9999999)",
            trigger: "blur",
            max: 9999999,
            min: 0,
            type: "number",
          },
        ],
        cycle: [
          {
            required: true,
            message: "请输入周期",
            trigger: "blur",
            type: "number",
            message: "请输入总条数(0-99999)",

            min: 0,
            max: 99999,
          },
        ],
      },
    };
  },
  created() {
    // this.getLawListTitleFn();
    this.getlabelListFn();
  },
  methods: {
    sumInput(value) {
      if (value.length > 7) {
        this.form.sum = parseInt(value.slice(0, 7));
      }
    },
    cycleInput(value) {
      if (value.length > 5) {
        this.form.cycle = parseInt(value.slice(0, 5));
      }
    },
    // 去除标签
    removeTag(v) {
      if (v.content == this.label) {
        this.label = "";
      }
      this.label;
      let labelList = this.form.labelList.filter((item) => item.id != v.id);
      this.$set(this.form, "labelList", labelList);
      // console.log(this.form);
    },
    // 获取标签
    async getlabelListFn() {
      let { code, rows } = await getlabelListApi();
      if (code != 200) return;
      rows.forEach((item) => {
        item.value = item.content;
      });

      this.labelShowList = rows;
    },
    // async getLawListTitleFn() {
    //   // 类型还未定义对应的值，后期还需要更改
    //   let { code, data } = await getLawListTitleApi();
    //   let smallType = [];
    //   if (code == 200) {
    //     data.forEach((item) => {
    //       switch (item.type) {
    //         case "法规":
    //           smallType.push({
    //             label: item.type,
    //             value: "1",
    //           });
    //           break;
    //         case "行政法规":
    //           smallType.push({
    //             label: item.type,
    //             value: "2",
    //           });
    //           break;
    //         case "监察法规":
    //           smallType.push({
    //             label: item.type,
    //             value: "3",
    //           });
    //           break;
    //       }
    //     });
    //   }

    //   this.smallLaw = smallType;
    // },
    querySearchAsync(queryString, cb) {
      var labelShowList = this.labelShowList;

      var results = queryString
        ? labelShowList.filter(this.createStateFilter(queryString))
        : labelShowList;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 300);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      let index = this.form.labelList.findIndex((v) => v.id == item.id);

      if (index == -1) {
        this.form.labelList.push(item);
      }
      this.label = "";
    },
    // 重设表单
    resetForm(formName) {
      this.form = {
        id: "",
        source: "",
        type: "",
        status: "",
        url: "",
        remark: "",
        sum: "",
        current: "",
        lawType: "",
        lastTime: "",
        cycle: "",
        secretLevel: "",
      };
      this.$refs[formName].resetFields();
    },
    // 新增
    async addFn() {
      const _this = this;
      _this.form.status = 1;

      let { code, msg } = await getCrawlerAddApi(_this.form);
      _this.$message({
        type: "success",
        message: msg,
      });
      if (code != 200) return;
      _this.close();
      _this.$emit("eventGetCrawlerList");
    },
    // 回显修改数据
    echo(row) {
      const _this = this;
      let arr = ["法律", "法规", "法则"];
      if (arr.includes(row.type)) {
        _this.isSmallLaw = true;
      } else {
        _this.isSmallLaw = false;
      }
      // 为1是法律
      if (row.lawType) {
        row.lawType = changeLawType(row.lawType);
      }
      // console.log(, "这是row哦！");
      if (row.labelList.length > 0) {
        row.labelList.forEach((item) => {
          item.value = item.content;
        });
      }
      _this.form = row;
    },
    //   保存数据
    async saveFn() {
      const _this = this;

      if (typeof _this.form.type == "string") {
      }
      let flag = await _this.$refs.form.validate();
      // 是否是字符串，是就转换成数字
      let isString = isNaN(Number(_this.form.type));

      if (isString) {
        _this.form.type = changeType(_this.form.type);
      }

      if (!flag) return;
      // 新增
      if (!_this.form.id) {
        _this.addFn();

        return;
      }

      // console.log(_this.form, "编辑编辑");

      let { code, msg } = await getCrawlerEditApi(_this.form);
      if (code == 200) {
        _this.$message({
          type: "success",
          message: msg,
        });
        _this.close();
        this.$emit("eventGetCrawlerList");
      }
      //   console.log(, "不知道我定不定的住");
    },
    rankChange(rank) {
      console.log(rank);
    },
    //   选择类型
    selectType(type) {
      // 是法律时候有法律小分类
      const _this = this;

      if (type == 1) {
        _this.isSmallLaw = true;
      } else {
        _this.isSmallLaw = false;
        _this.form.lawType = "";
      }
    },
    close() {
      const _this = this;
      _this.$refs.form.clearValidate();
      _this.$emit("update:dialogVisible", false);
      _this.form = {
        id: "",
        source: "",
        type: "",
        status: "",
        url: "",
        remark: "",
        sum: "",
        current: "",
        lawType: "",
        lastTime: "",
        cycle: "",
        secretLevel: "A",
        labelList: [],
      };
      _this.$refs.form.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
</style>
<style lang="scss" scoped>
::v-deep .el-autocomplete {
  width: 100%;
}
.tag-box {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  .tag {
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
</style>